package com.franklin.validation.core.webflux.override;

import com.franklin.validation.core.constants.Constants;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * Description : 向Header中添加requestId
 * Create By: Franklin
 * Date : 2020/6/15 19:35
 */
public class ServerHttpRequestDecorator extends org.springframework.http.server.reactive.ServerHttpRequestDecorator {

    private final HttpHeaders oldHeaders;
    private final String requestId;

    public ServerHttpRequestDecorator(ServerHttpRequest oldReq, HttpHeaders oldHeaders, String requestId) {
        super(oldReq);
        this.oldHeaders = oldHeaders;
        this.requestId = requestId;
    }

    @Override
    public HttpHeaders getHeaders() {
        long contentLength = this.oldHeaders.getContentLength();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.putAll(super.getHeaders());
        httpHeaders.add(Constants.REQUEST_ID,this.requestId);
        if (contentLength > 0) {
            httpHeaders.setContentLength(contentLength);
        } else {
            httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
        }
        return httpHeaders;
    }
}
